package cc.linker.steplink.crm.merchant.service;

import cc.linker.steplink.crm.commons.FeeConstants;
import cc.linker.steplink.crm.commons.TradeTypeConstants;
import cc.linker.steplink.crm.merchant.dao.RefundDao;
import cc.linker.steplink.crm.merchant.service.acs.RechargeService;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.pojo.acs.AccountInfo;
import cc.linker.steplink.crm.merchanth5.pojo.acs.RefundParamPo;
import cc.linker.steplink.crm.merchanth5.dao.acs.ProtectRecordDao;
import cc.linker.steplink.crm.merchanth5.service.acs.ProtectRecordService;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.merchanth5.service.common.SmsService;
import cc.linker.steplink.crm.merchanth5.service.tl.LedgerProcessService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class RefundService {

    @Autowired
    private RefundDao refundDao;
    @Autowired
    private SmsService smsService;
    @Autowired
    private PurchaseProcessService purchaseProcessService;
    @Autowired
    private LedgerProcessService ledgerProcessService;
    @Autowired
    private ProtectRecordDao protectRecordDao;
    @Autowired
    private ProtectRecordService protectRecordService;
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;
    @Autowired
    private RechargeService rechargeService;

    public Object getProtectInfo(Map<String, Object> params) {
        Map map = refundDao.getProtectInfo(params);
        List<Map> consultList = refundDao.getConsultList(params);
        for (Map consultMap : consultList) {
            if (!StringUtils.isEmpty(consultMap.get("consultImages"))) {
                JSONArray consultImages = JSON.parseArray(consultMap.get("consultImages").toString());
                consultMap.put("consultImages", consultImages);
            }
        }
        if (map != null) {
            map.put("consultList", consultList);
        }
        return map;
    }

    public List<Map> getConsultList(Map<String, Object> params) {
        return refundDao.getConsultList(params);
    }


    /**
     * @Description: 用户维权操作
     * @param: protectCode 维权编号
     * @param: refundStatus 退款状态
     * @param: reasonContent 拒绝原因
     * @param: recId 订单商品表id
     * @Return: void
     * @Author: ch
     * @Date: 2020/02/12 14:48
     * @Version: 1.11.10
     **/
    public void updateStatus(Map<String, Object> params) {
        if (params.get("refundStatus") != null) {
            Integer refundStatus = Integer.valueOf(params.get("refundStatus").toString());
            String consultStatus = "";
            String consultContent = "";
            if (refundStatus == 3) {
                //延长收货操作时间加7天
                refundDao.extendTime(params);
            } else {
                refundDao.updaterefundStatus(params);
                RefundParamPo rePo = refundDao.getRefundParamPo(params);
                if (refundStatus == 2) {
                    //等待发货(同意退款退货)
                    LOGGER.info("等待发货(同意退款退货)");
                    consultStatus = "已同意退款申请,等待买家退货";
                    if (rePo.getMallsGoodsId()!=null){
//                        RefundParamPo rePo2 = refundDao.getRefundParamPo(params);
                        RefundParamPo rePo2 = refundDao.getRefundAddress(rePo.getMallsGoodsId());
                        consultContent = "退货地址：" + (rePo2.getReturnAddress() == null ? "" : rePo2.getReturnAddress() + "，") +
                                (rePo2.getReturnPeople() == null ? "" : (rePo2.getReturnPeople() + "，")) + (rePo2.getReturnPhone() == null ? "" : rePo2.getReturnPhone());
                    }else {
                        consultContent = "退货地址：" + (rePo.getReturnAddress() == null ? "" : rePo.getReturnAddress() + "，") +
                                (rePo.getReturnPeople() == null ? "" : (rePo.getReturnPeople() + "，")) + (rePo.getReturnPhone() == null ? "" : rePo.getReturnPhone());

                    }
                } else if (refundStatus == 4 || refundStatus == 7) {
                    //拒绝收货 退款失败
                    LOGGER.info("拒绝收货");
                    consultStatus = "拒绝了本次退款申请,等待买家修改";
                    consultContent = "拒绝原因：";
                    if (params.get("reasonContent") != null) {
                        consultContent = consultContent + params.get("reasonContent").toString();
                    }
                    sendMsg(rePo.getOrgId(), rePo.getRefundPhone(), "9013", rePo.getOrderSn());
                    if (refundStatus == 7) {
                        //结算中心账单修改
                        protectRecordService.revokeAction(rePo.getOrderSn(), rePo.getOrgId(), rePo.getRecId(), refundStatus);
                    }
                } else if (refundStatus == 5) {
                    //查询订单还有没有未完成
                    Map<String, Object> param = new HashMap<String, Object>();
                    param.put("orderSn", rePo.getOrderSn());
                    param.put("orderId", rePo.getOrderId());
                    param.put("recId", rePo.getRecId());
                    Integer count = refundDao.getOtherOrderRefundCount(param);
                    if (count == 0) {
                        //所有退款完成
                        //1更改订单退款状态
                        param.put("refundState", 3);
                        protectRecordDao.updateOrderRefundState(param);
                    }
                    //同意退款
                    LOGGER.info("同意退款");
                    consultStatus = "同意退款给买家，本次维权结束";
                    consultContent = "退款金额：¥" + rePo.getRefundAmount();
                    //sendMsg(rePo.getOrgId(), rePo.getRefundPhone(), "9012", rePo.getOrderSn());
                    // 添加退款记录
                    Map<String,Object> temps = new HashMap<>();
                    Long recId =rePo.getRecId();
                    temps.put("recId",recId);
                    temps.put("remark","卖家同意退款");
                    temps.put("status",1);
                    purchaseProcessDao.addRefundLogs(temps);
                    try {
                        refundToUser(rePo);
                    } catch (Exception e) {
                        LOGGER.info("退款异常！", e);
                        Map<String,Object> temp = new HashMap<>();
                        temp.put("recId",recId);
                        temp.put("remark","退款失败");
                        temp.put("status",3);
                        purchaseProcessDao.addRefundLogs(temp);
                    }

                }
                params.put("consultStatus", consultStatus);
                params.put("consultContent", consultContent);
                addConsult(params);
            }

        }
    }


    public void addConsult(Map<String, Object> params) {
        //发起方卖家
        params.put("consultObj", 2);
        if (!StringUtils.isEmpty(params.get("consultImages"))) {
            String consultImages = JSONArray.toJSONString(params.get("consultImages"));
            params.put("consultImages", consultImages);
        }
        refundDao.addConsult(params);
    }

    public void sendMsg(String orgId, String phone, String businessType, String orderSn) {
        try {
            // 发送信息
            Map<String, Object> nvps = new HashMap<>();
            nvps.put("businessType", businessType);
            nvps.put("mobilNumber", phone);
            nvps.put("params", "{order=" + orderSn + "}");
            String result = smsService.sendMsg(orgId, nvps);
            LOGGER.info("退款操作短信发送结果===" + result);
        } catch (Exception e) {
            LOGGER.info("短信网关错误===" + e);
        }
    }


    /**
     * 同意退款调用接口
     *
     * @param rePo
     */
    public void refundToUser(RefundParamPo rePo) {
        LOGGER.info("refundToUser===[{}]", JSON.toJSONString(rePo));
        //统一退款，修改订单表，订单商品表，结算中心表(退款状态和endTime)，冻结余额
        protectRecordService.overAction(rePo.getOrderSn(), rePo.getOrgId(), rePo.getRecId());
        //调用退款接口
        if (rePo.getPayType() != null && rePo.getPayType() == 1) {
            //微信支付
            Map<String, String> res = new HashMap<>();
            Long refundAmount = 0L;
            if (rePo.getRefundAmount() == null || rePo.getOrderTotalPrice() == null || rePo.getOrderAmount() == null || rePo.getRefundAmount() > rePo.getOrderTotalPrice()) {
                throw GlobalException.build("退款金额超过订单总金额或订单总金额为空或订单付款总现金为空");
            } else if (rePo.getRefundAmount().equals(rePo.getOrderTotalPrice())) {
                LOGGER.info("微信全额退款开始");
                //退款金额等于订单总价（全额）
                //用订单实付金额去退款
                if (rePo.getOrderAmount() > 0) {
                    refundAmount = (new Double((rePo.getOrderAmount() * 100))).longValue();
                    res = purchaseProcessService.refund(rePo.getOrderSn(), rePo.getRefundReason(), (new Double((rePo.getOrderAmount() * 100))).intValue(),rePo.getPaySn());
                }
                sendMsg(rePo.getOrgId(), rePo.getRefundPhone(), "9012", rePo.getOrderSn());
                sendMsg(rePo.getOrgId(), rePo.getRefundPhone(), "9014", rePo.getOrderSn());
                LOGGER.info("微信全额退款结束");
            } else {
                LOGGER.info("微信部分退款开始");
                //退款金额小于订单总金额（可能已有其他退款，需要金币抵扣，不能直接用退款金额）
                //结算中心查询该recId退款的总金额
                if(rePo.getRefundAmount()>0){
                    refundAmount = protectRecordDao.getAllAmountByRecId(rePo.getRecId());
                    if (refundAmount > 0) {
                        res = purchaseProcessService.refund(rePo.getOrderSn(), rePo.getRefundReason(), (new Long(refundAmount).intValue()),rePo.getPaySn());
                    }
                }
                sendMsg(rePo.getOrgId(), rePo.getRefundPhone(), "9012", rePo.getOrderSn());
                sendMsg(rePo.getOrgId(), rePo.getRefundPhone(), "9014", rePo.getOrderSn());
                LOGGER.info("微信部分退款结束");
            }
            //返回参数入库用于查询退款结果
            if (res != null && res.size() > 0) {
                res.put("protectCode", rePo.getProtectCode());
                refundDao.updaterefundAgg(res);
                Long recId =rePo.getRecId();
                Map<String, Object> temps = new HashMap<>();
                temps.put("recId", recId);
                temps.put("remark", "到账成功");
                temps.put("status", 2);
                purchaseProcessDao.addRefundLogs(temps);
            }else {
                Long recId =rePo.getRecId();
                Map<String, Object> temps = new HashMap<>();
                temps.put("recId", recId);
                if(refundAmount==0){
                    temps.put("remark", "到账成功");
                    temps.put("status", 2);
                    purchaseProcessDao.addRefundLogs(temps);
                }else {
                    temps.put("remark", "到账失败");
                    temps.put("status", 3);
                    purchaseProcessDao.addRefundLogs(temps);
                }

            }
        } else if (rePo.getPayType() != null && (rePo.getPayType() == 2 || rePo.getPayType() == 3)) {
            if(rePo.getRefundAmount()>0){
                //新表是否有数据（后面可以去掉）
                Integer protectGoodsCount = purchaseProcessDao.getProtectGoodsCount(rePo.getOrderSn());
                if(protectGoodsCount==0){
                    //老逻辑
                    oldTlRefund(rePo, rePo.getPayType());
                }else {
                    LOGGER.info("新退款开始");
                    //新逻辑
                    newTlRefund(rePo, rePo.getPayType());
                }
            }else {
                Long recId =rePo.getRecId();
                Map<String, Object> temps = new HashMap<>();
                temps.put("recId", recId);
                temps.put("remark", "到账成功");
                temps.put("status", 2);
                purchaseProcessDao.addRefundLogs(temps);

            }

        }
    }

    public void newTlRefund(RefundParamPo rePo,Integer payMode){
        String orgId = rePo.getOrgId();
        // 根据配置读取 服务费、推荐费、联汇抽成、大b抽成分别给谁
        String orgUid = purchaseProcessDao.getAccountUidByOrgId(orgId);
        List<Map<String, Object>> cashSplitItems = new ArrayList<>();
        List<Map<String, Object>> balanceSplitItems = new ArrayList<>();
        //List<Map<String, Object>> tlParamList = purchaseProcessDao.getTlParamList(rePo.getOrderSn());
        List<Map<String, Object>> tlParamList = purchaseProcessDao.getTlParamListByRecId(rePo.getRecId());
        //销售商
        Map<String, Object> cashSplitItem = new HashMap<>();
        Map<String, Object> balanceSplitItem = new HashMap<>();
        //供货商
        Map<String, Object> cashSplitItemg = new HashMap<>();
        Map<String, Object> balanceSplitItemg = new HashMap<>();
        List<AccountInfo> subAccountList = new ArrayList<>();
        List<AccountInfo> balanceList = new ArrayList<>();
        Map<String, Integer> subAccountMap = new HashMap<>();
        Map<String, Integer> subAccountMapg = new HashMap<>();
        Map<String, Integer> balanceAccountMap = new HashMap<>();
        Map<String, Integer> balanceAccountMapg = new HashMap<>();
        String mallsBelongId = "";
        String mallsOrgId = "";
        String mallsOrgUid = orgUid;
        String mallsBelongUid = "";
        // 小b和大b要去查uid
        String belongUid = "";
        String belongId = "";
        for(Map tlParam  : tlParamList){
            Integer tradeType = -1;
            if(tlParam.get("tradeType")!=null){
                tradeType = Integer.valueOf(tlParam.get("tradeType").toString());
            }
            Integer amount = 0;
            if(tlParam.get("amount")!=null){
                amount = Integer.valueOf(tlParam.get("amount").toString());
            }
            Integer score = 0;
            if(tlParam.get("score")!=null){
                score = Integer.valueOf(tlParam.get("score").toString());
                amount = amount - score;
            }
            Integer amountType = 0;
            if(tlParam.get("amountType")!=null){
                amountType = Integer.valueOf(tlParam.get("amountType").toString());
            }
            if(!StringUtils.isEmpty(tlParam.get("belongId"))){
                belongId = tlParam.get("belongId").toString();
            }
            String receiveUser = "";
            if(!StringUtils.isEmpty(tlParam.get("receiveUser"))){
                receiveUser = tlParam.get("receiveUser").toString();
            }
            String payUser = "";
            if(!StringUtils.isEmpty(tlParam.get("payUser"))){
                payUser = tlParam.get("payUser").toString();
            }
            Long mallsGoodsId = null;
            if(!StringUtils.isEmpty(tlParam.get("mallsGoodsId"))){
                mallsGoodsId = Long.valueOf(tlParam.get("mallsGoodsId").toString());
            }
            if(!StringUtils.isEmpty(mallsGoodsId)){
                mallsOrgId = purchaseProcessDao.getOrgIdByGoodsId(mallsGoodsId);
            }
            if(!StringUtils.isEmpty(mallsOrgId) && !mallsOrgId.equals(orgId)){
                mallsOrgUid = purchaseProcessDao.getAccountUidByOrgId(mallsOrgId);
            }
            if(StringUtils.isEmpty(belongUid)){
                belongUid = purchaseProcessDao.getAccountUidByCustomerId(belongId);
            }
            if(mallsGoodsId!=null){
                if(StringUtils.isEmpty(mallsBelongId)){
                    mallsBelongId = purchaseProcessDao.getBelongIdByGoodsId(mallsGoodsId);
                    mallsBelongUid = purchaseProcessDao.getAccountUidByCustomerId(mallsBelongId);
                }
            }
            Integer mapAmount = 0;
            if (!StringUtils.isEmpty(cashSplitItem.get("amount"))) {
                mapAmount = (Integer) cashSplitItem.get("amount");
            }
            Integer mapAmountg = 0;
            if (!StringUtils.isEmpty(cashSplitItemg.get("amount"))) {
                mapAmountg = (Integer) cashSplitItemg.get("amount");
            }
            Integer mapScore = 0;
            Integer mapScoreg = 0;
            if(score>0) {
                if (!StringUtils.isEmpty(balanceSplitItem.get("amount"))) {
                    mapScore = (Integer) balanceSplitItem.get("amount");
                }
                if (!StringUtils.isEmpty(balanceSplitItemg.get("amount"))) {
                    mapScoreg = (Integer) balanceSplitItemg.get("amount");
                }
            }
            if(tradeType.equals(TradeTypeConstants.RECOMMENDS_FEE)){
                //推荐
                subAccountMap.put(FeeConstants.RECOMMEND_FEE, amount);
                if(score>0){
                    balanceAccountMap.put(FeeConstants.RECOMMEND_FEE, score);
                }
            }else if( tradeType.equals(TradeTypeConstants.SERVER_FEE)){
                //服务
                subAccountMap.put(FeeConstants.SERVICE_COIN_FEE, amount);
                if(score>0){
                    balanceAccountMap.put(FeeConstants.SERVICE_COIN_FEE, score);
                }
            }else if( tradeType.equals(TradeTypeConstants.GOODS_PLATFORM_FEE)){
                //平台
                subAccountMap.put(FeeConstants.ORG_DRAW_FEE, amount);
                if(score>0){
                    balanceAccountMap.put(FeeConstants.ORG_DRAW_FEE, score);
                }
            }else if( tradeType.equals(TradeTypeConstants.PAY_CENTAGE_FEE)){
                //支付抽成（大b）
                subAccountMapg.put(FeeConstants.ORG_DRAW_FEE, amount);
                if(score>0){
                    balanceAccountMapg.put(FeeConstants.ORG_DRAW_FEE, score);
                }
            }else if( tradeType.equals(TradeTypeConstants.GOODS_LINK_PLATFORM_FEE)){
                //联汇
                subAccountMapg.put(FeeConstants.LINK_DRAW_FEE, amount);
                if(score>0){
                    balanceAccountMapg.put(FeeConstants.LINK_DRAW_FEE, score);
                }
            }else if( tradeType.equals(TradeTypeConstants.CREATE_FEE)){
                //创作
                subAccountMap.put(FeeConstants.ORIGINAL_FEE, amount);
                if(score>0){
                    balanceAccountMap.put(FeeConstants.ORIGINAL_FEE, score);
                }
            }else if(tradeType.equals(TradeTypeConstants.PURCHASE_FEE)){
                //采购
                cashSplitItem.put("bizUserId", (StringUtils.isEmpty(belongId)) ? orgUid : belongUid);
                cashSplitItem.put("amount", (mapAmount - amount));
                if(score>0){
                    balanceSplitItem.put("bizUserId", (StringUtils.isEmpty(belongId)) ? orgUid : belongUid);
                    balanceSplitItem.put("amount", (mapScore - score));
                }
            }else if(tradeType.equals(TradeTypeConstants.SPREAD_FEE)){
                //推广佣金
                //销售商
                cashSplitItem.put("bizUserId", (StringUtils.isEmpty(belongId)) ? orgUid : belongUid);
                cashSplitItem.put("amount", (mapAmount + amount));

                //供货商
                cashSplitItemg.put("bizUserId", mallsBelongUid);
                cashSplitItemg.put("amount", (mapAmountg - amount-score));
                if(score>0){
                    //销售商
                    balanceSplitItem.put("bizUserId", (StringUtils.isEmpty(belongId)) ? orgUid : belongUid);
                    balanceSplitItem.put("amount", (mapScore + score));

                }

            } else if(tradeType.equals(TradeTypeConstants.TRADE_SERVER_FEE)){
                //交易手续费
                if((!StringUtils.isEmpty(belongId) && !belongId.equals(payUser)) || (StringUtils.isEmpty(belongId) && !orgId.equals(payUser))){
                    //供货商(大b供货商)
//                    splitItemIncomeg.put("bizUserId", mallsBelongUid);
                    cashSplitItemg.put("bizUserId", StringUtils.isEmpty(mallsBelongUid) ? mallsOrgUid : mallsBelongUid);
                    cashSplitItemg.put("amount", (mapAmountg - amount));
                    if (score>0){
                        balanceSplitItemg.put("bizUserId", StringUtils.isEmpty(mallsBelongUid) ? mallsOrgUid : mallsBelongUid);
                        balanceSplitItemg.put("amount", (mapScoreg - score));
                    }
                }else{
                    //普通商品
//                    splitItemIncome.put("bizUserId", (StringUtils.isEmpty(belongId)) ? orgUid : belongUid);
                    cashSplitItem.put("bizUserId", (StringUtils.isEmpty(belongId)) ? orgUid : belongUid);
                    cashSplitItem.put("amount", (mapAmount - amount));
                    if (score>0){
                        balanceSplitItem.put("bizUserId", (StringUtils.isEmpty(belongId)) ? orgUid : belongUid);
                        balanceSplitItem.put("amount", (mapScore - score));
                    }
                }

            }else if(tradeType.equals(TradeTypeConstants.REJUVENATE_FEE)){
                //返润佣金
                cashSplitItem.put("bizUserId", (StringUtils.isEmpty(belongId)) ? orgUid : belongUid);
                cashSplitItem.put("amount", (mapAmount - amount));
                if (score>0){
                    balanceSplitItem.put("bizUserId", (StringUtils.isEmpty(belongId)) ? orgUid : belongUid);
                    balanceSplitItem.put("amount", (mapScore - score));
                }
            }
            if( tradeType.equals(TradeTypeConstants.DEAL_FEE) || tradeType.equals(TradeTypeConstants.DEAL_PLATFORM_FEE)){
                if(amountType == 1) {
                    // 小b要去查uid
                    if((!StringUtils.isEmpty(belongId) && !belongId.equals(receiveUser)) || (StringUtils.isEmpty(belongId) && !orgId.equals(receiveUser))){
                        //供货商的商品收益
                        cashSplitItemg.put("bizUserId", (StringUtils.isEmpty(mallsBelongId)) ? mallsOrgUid : mallsBelongUid);
                        cashSplitItemg.put("amount", (mapAmountg + amount));
                        if (score>0){
                            balanceSplitItemg.put("bizUserId", (StringUtils.isEmpty(mallsBelongId)) ? mallsOrgUid : mallsBelongUid);
                            balanceSplitItemg.put("amount", (mapScoreg + score));
                        }
                    }else {
                        //销售商商品收益或者普通商品收益
                        cashSplitItem.put("bizUserId", (StringUtils.isEmpty(belongId)) ? orgUid : belongUid);
                        cashSplitItem.put("amount", (mapAmount + amount));
                        if (score>0){
                            balanceSplitItem.put("bizUserId", (StringUtils.isEmpty(belongId)) ? orgUid : belongUid);
                            balanceSplitItem.put("amount", (mapScore + score));
                        }
                    }
                }else if(tradeType.equals(TradeTypeConstants.SERVER_SCORE) && amountType == 2){
                    //服务
                    subAccountMap.put( FeeConstants.SERVICE_COIN_FEE, amount);
                    if(score>0){
                        balanceAccountMap.put(FeeConstants.SERVICE_COIN_FEE, score);
                    }
                }
            }
        }
        for (String s : subAccountMap.keySet()) {
            subAccountList.add(purchaseProcessService.getAccountMap(s, subAccountMap.get(s), orgId, payMode));
        }
        for (String s : balanceAccountMap.keySet()) {
            balanceList.add(purchaseProcessService.getAccountMap(s, balanceAccountMap.get(s), orgId, payMode));
        }
        for (String s : subAccountMapg.keySet()) {
            if(StringUtils.isEmpty(mallsOrgId)){
                mallsOrgId = orgId;
            }
            subAccountList.add(purchaseProcessService.getAccountMap(s, subAccountMapg.get(s), mallsOrgId, payMode));
        }
        for (String s : balanceAccountMapg.keySet()) {
            if(StringUtils.isEmpty(mallsOrgId)){
                mallsOrgId = orgId;
            }
            balanceList.add(purchaseProcessService.getAccountMap(s, balanceAccountMapg.get(s), mallsOrgId, payMode));
        }
        Map<String, Integer> collect = subAccountList.stream()
                .collect(Collectors.groupingBy(AccountInfo::getCustomerId, Collectors.summingInt(AccountInfo::getAmount)));
        Map<String, Object> splitItemIncomeOrg = new HashMap<>();
        Map<String, Object> balanceItemIncomeOrg = new HashMap<>();
        //销售商亏损金额
        int salerLossAmount = 0;
        //供货商亏损金额
        int mallsLossAmount = 0;
        collect.forEach((x, y) -> {
            if("#yunBizUserId_B2C#".equals(x) || x.equals(orgUid)){
                // 平台营销资金账户则加入到商品收益的平台费中
                Integer amount = 0;
                if(!StringUtils.isEmpty(splitItemIncomeOrg.get("amount"))){
                    amount = (Integer) splitItemIncomeOrg.get("amount");
                }
                amount = amount + y;
                splitItemIncomeOrg.put("bizUserId",orgUid);
                splitItemIncomeOrg.put("amount",amount);
            }else {
                if(y>0){
                    Map<String, Object> cashSplitItemL = new HashMap<>();
                    cashSplitItemL.put("bizUserId", x);
                    cashSplitItemL.put("amount", y);
                    cashSplitItems.add(cashSplitItemL);
                }
            }
        });
        if(!splitItemIncomeOrg.isEmpty()){
            Integer mapAmount = 0;
            if (!StringUtils.isEmpty(splitItemIncomeOrg.get("amount"))) {
                mapAmount = (Integer) splitItemIncomeOrg.get("amount");
            }
            if(mapAmount>0){
                cashSplitItems.add(splitItemIncomeOrg);
            }
            if (mapAmount<0){
                salerLossAmount += mapAmount;
            }
        }
        Integer mapAmountg = 0;
        if (!cashSplitItemg.isEmpty()){
            if (!StringUtils.isEmpty(cashSplitItemg.get("amount"))) {
                mapAmountg = (Integer) cashSplitItemg.get("amount");
            }
            if(mapAmountg>0){
                cashSplitItems.add(cashSplitItemg);
            }
            if (mapAmountg<0){
                mallsLossAmount += mapAmountg;
            }
        }
        if (!cashSplitItem.isEmpty()){
            Integer mapAmount = 0;
            if (!StringUtils.isEmpty(cashSplitItem.get("amount"))) {
                mapAmount = (Integer) cashSplitItem.get("amount");
            }
            if(mapAmount>0){
                if(mapAmountg<0){
                    mapAmount += mapAmountg;
                    cashSplitItem.put("amount",mapAmount);
                }
                cashSplitItems.add(cashSplitItem);
            }
            if (mapAmount<0){
                salerLossAmount += mapAmount;
            }
        }

        Integer cashAmount = 0;
        for (Map<String, Object> cashSplitItemA : cashSplitItems){
            Integer amount = 0;
            if(!StringUtils.isEmpty(cashSplitItemA.get("amount"))){
                amount = (Integer) cashSplitItemA.get("amount");
            }
            cashAmount = cashAmount+ amount;
        }
        //金币
        //List<Map<String, Object>> balanceSplitItems = null;
        Map<String, Integer> collectBalance = balanceList.stream()
                .collect(Collectors.groupingBy(AccountInfo::getCustomerId, Collectors.summingInt(AccountInfo::getAmount)));
        collectBalance.forEach((x, y) -> {
            if(!"#yunBizUserId_B2C#".equals(x)){
                if(x.equals(orgUid)){
                    // 平台营销资金账户则加入到商品收益的平台费中
                    Integer amount = 0;
                    if(!StringUtils.isEmpty(balanceItemIncomeOrg.get("amount"))){
                        amount = (Integer) balanceItemIncomeOrg.get("amount");
                    }
                    amount = amount + y;
                    balanceItemIncomeOrg.put("bizUserId",orgUid);
                    balanceItemIncomeOrg.put("amount",amount);
                }else {
                    if(y>0){
                        Map<String, Object> balanceSplitItemL = new HashMap<>();
                        balanceSplitItemL.put("bizUserId", x);
                        balanceSplitItemL.put("amount", y);
                        balanceSplitItems.add(balanceSplitItemL);
                    }
                }
            }
        });
        if(!balanceItemIncomeOrg.isEmpty()){
            Integer mapScore = 0;
            if (!StringUtils.isEmpty(balanceItemIncomeOrg.get("amount"))) {
                mapScore = (Integer) balanceItemIncomeOrg.get("amount");
            }
            if(mapScore>0){
                balanceSplitItems.add(balanceItemIncomeOrg);
            }
            if (mapScore<0){
                salerLossAmount += mapScore;
            }
        }
        Integer mapScoreg = 0;
        if (!balanceSplitItemg.isEmpty()){
            if (!StringUtils.isEmpty(balanceSplitItemg.get("amount"))) {
                mapScoreg = (Integer) balanceSplitItemg.get("amount");
            }
            if(mapScoreg>0){
                balanceSplitItems.add(balanceSplitItemg);
            }
            if (mapScoreg<0){
                mallsLossAmount += mapScoreg;
            }
        }
        if (!balanceSplitItem.isEmpty()){
            Integer mapScore = 0;
            if (!StringUtils.isEmpty(balanceSplitItem.get("amount"))) {
                mapScore = (Integer) balanceSplitItem.get("amount");
            }
            if(mapScore>0){
                if(mapAmountg<0){
                    mapScore += mapAmountg;
                    balanceSplitItem.put("amount",mapScore);
                }
                balanceSplitItems.add(balanceSplitItem);
            }
            if (mapScore<0){
                salerLossAmount += mapScore;
            }
        }

        Integer balanceAmount = 0;
        if(balanceSplitItems!=null && balanceSplitItems.size()>0){
            for (Map<String, Object> balanceSplitItemA : balanceSplitItems){
                Integer score = 0;
                if(!StringUtils.isEmpty(balanceSplitItemA.get("amount"))){
                    score = (Integer) balanceSplitItemA.get("amount");
                }
                balanceAmount = balanceAmount+ score;
            }
        }

        //[{"customerId":"C20190906Bgw72a","amount":100,"plantAmount":0}，
        // {"customerId":"9aa9e48c-481f-4690-8755-b9db9b330fee","amount":100,"plantAmount":20}]
        // 现金分账明细，JSON字符串
        String cashSplitItemsString = JSON.toJSONString(cashSplitItems);
        String balanceSplitItemsString = null;
        if(balanceSplitItems!=null && balanceSplitItems.size()>0){
            balanceSplitItemsString = JSON.toJSONString(balanceSplitItems);
        }
        LOGGER.info("退款通联参数===[{}]", cashSplitItemsString);
        Map<String, Object> map = ledgerProcessService.refund(rePo.getOrderSn(), balanceAmount.toString(), balanceSplitItemsString, cashAmount.toString(), cashSplitItemsString,rePo.getPaySn(),payMode);
        LOGGER.info("通联部分退款结束");
        map.put("recId", rePo.getRecId());
        if (balanceAmount == 0) {
            //没有金币(一次回调)
            map.put("tlRefundNum", 1);
        } else {
            //有金币(两次回调)
            map.put("tlRefundNum", 0);
        }
        if(cashAmount==0 && balanceAmount>0){
            //全额的没有回调
            Map refundMap = new HashMap();
            refundMap.put("orderSn",rePo.getPaySn());
            refundMap.put("orderSn",map.get("refundOrderSn"));
            refundMap.put("status","20");
            purchaseProcessService.refundCallBack(refundMap);
            map.put("tlRefundNum", 1);
        }
        refundDao.updateTlStatus(map);
        try {
            if ( mallsLossAmount < 0) {
                String lossOrgId = StringUtils.isEmpty(mallsBelongId)?mallsOrgId:mallsBelongId;
                //订单更新
                purchaseProcessDao.updateLossOrder(null, mallsLossAmount,salerLossAmount, rePo.getOrderSn(),lossOrgId,null);
                rechargeService.isLoss(rePo.getOrderSn());
            }
            if ( salerLossAmount  < 0) {
                String lossSalerOrgId = StringUtils.isEmpty(belongId)?orgId:belongId;
                //订单更新
                purchaseProcessDao.updateLossOrder(null, mallsLossAmount,salerLossAmount, rePo.getOrderSn(),null,lossSalerOrgId);
                rechargeService.isLoss(rePo.getOrderSn());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void oldTlRefund(RefundParamPo rePo,Integer payMode){
        //通联支付
        if (rePo.getRefundAmount() == null || rePo.getOrderTotalPrice() == null || rePo.getRefundAmount() > rePo.getOrderTotalPrice()) {
            throw GlobalException.build("退款金额超过订单总金额或订单总金额为空");
        } else if (rePo.getRefundAmount().equals(rePo.getOrderTotalPrice())) {
            LOGGER.info("通联全额退款开始");
            //全额退款
            Map<String, Object> map = ledgerProcessService.refundAll(rePo.getOrderSn());
            LOGGER.info("通联全额退款结束");
            map.put("recId", rePo.getRecId());
            if (rePo.getRefundAmount().equals(rePo.getOrderAmount())) {
                //没有金币(一次回调)
                map.put("tlRefundNum", 1);
            } else {
                //有金币(两次回调)
                map.put("tlRefundNum", 0);
            }
            refundDao.updateTlStatus(map);
        } else {
            LOGGER.info("通联部分退款开始");
            //部分退款（可能已有其他退款，需要金币抵扣，不能直接用退款金额）
            //根据订单号获取购买信息
            Map<String, String> purchaseMap = getPurchaseInfo(rePo.getOrderSn());
            //退款总金额
            Long cashAmount = 0l;
            //机构退款金额
            Long unionbarleyAmount = 0l;
            //联汇退款金额
            Long linkerTakeAmount = 0l;
            //退款金币
            Long balanceAmount = 0l;
            String cashSplitItems = null;
            String balanceSplitItems = null;
            //结算中心查询该退款的总金额
            cashAmount = protectRecordDao.getAllAmountByRecId(rePo.getRecId());
            //结算中心查询该退款的联汇手续费
            linkerTakeAmount = protectRecordDao.getLinkerAmountByRecId(rePo.getRecId());
            //结算中心查询该退款的金币退款
            balanceAmount = protectRecordDao.getBalanceAmountByRecId(rePo.getRecId());
            if (balanceAmount != 0) {
                List<Map<String, String>> balanceSplitItemsArr = new ArrayList<>();
                Map<String, String> balacnceMap = new HashMap<>();
                balacnceMap.put("customerId", purchaseMap.get("balanceCustomerId"));
                balacnceMap.put("splitAmount", balanceAmount.toString());
                balanceSplitItemsArr.add(balacnceMap);
                balanceSplitItems = JSONArray.toJSONString(balanceSplitItemsArr);
            }
            if (cashAmount != 0) {
                List<Map<String, String>> cashSplitItemsArr = new ArrayList<>();
                unionbarleyAmount = cashAmount - linkerTakeAmount;
                Map<String, String> unionbarleyMap = new HashMap<>();
                unionbarleyMap.put("bizUserId", purchaseMap.get("unionbarleyCustomerId"));
                unionbarleyMap.put("amount", unionbarleyAmount.toString());
                cashSplitItemsArr.add(unionbarleyMap);
                if (linkerTakeAmount != 0) {
                    Map<String, String> linkerMap = new HashMap<>();
                    linkerMap.put("bizUserId", purchaseMap.get("linkerCustomerId"));
                    linkerMap.put("amount", linkerTakeAmount.toString());
                    cashSplitItemsArr.add(linkerMap);
                }
                cashSplitItems = JSONArray.toJSONString(cashSplitItemsArr);
            }
            Map<String, Object> map = ledgerProcessService.refund(rePo.getOrderSn(), balanceAmount.toString(), balanceSplitItems, cashAmount.toString(), cashSplitItems,rePo.getPaySn(),payMode);
            LOGGER.info("通联部分退款结束");
            map.put("recId", rePo.getRecId());
            if (balanceAmount == 0) {
                //没有金币(一次回调)
                map.put("tlRefundNum", 1);
            } else {
                //有金币(两次回调)
                map.put("tlRefundNum", 0);
            }
            refundDao.updateTlStatus(map);
        }
    }

    /**
     * 根据订单号获取购买信息
     *
     * @param orderSn
     * @return
     */
    public Map<String, String> getPurchaseInfo(String orderSn) {
        //根据订单号获取购买信息
        Map<String, String> purchaseMap = refundDao.getPurchaseInfo(orderSn);
        String requestParams = purchaseMap.get("requestParams");
        String linkerTake = purchaseMap.get("linkerTake");
        String unionbarleyTake = purchaseMap.get("unionbarleyTake");
        String balanceCustomerId = null;
        String linkerCustomerId = null;
        String unionbarleyCustomerId = null;
        if (!StringUtils.isEmpty(requestParams)) {
            JSONObject parse = JSON.parseObject(requestParams);
            if (parse != null) {
                if (parse.get("balanceSplitItems") != null) {
                    String balanceSplitItems = parse.get("balanceSplitItems").toString();
                    if (!StringUtils.isEmpty(balanceSplitItems)) {
                        JSONArray balanceSplitItemsArr = JSON.parseArray(balanceSplitItems);
                        if (balanceSplitItemsArr != null && balanceSplitItemsArr.size() == 1) {
                            String balanceSplitItemsString = balanceSplitItemsArr.get(0).toString();
                            if (!StringUtils.isEmpty(balanceSplitItemsString)) {
                                JSONObject balanceSplitItemsObj = JSON.parseObject(balanceSplitItemsString);
                                if (balanceSplitItemsObj.get("customerId") != null) {
                                    balanceCustomerId = balanceSplitItemsObj.get("customerId").toString();
                                }
                            }
                        }
                    }
                }
                if (parse.get("cashSplitItems") != null) {
                    String cashSplitItems = parse.get("cashSplitItems").toString();
                    if (!StringUtils.isEmpty(cashSplitItems)) {
                        JSONArray cashSplitItemsArr = JSON.parseArray(cashSplitItems);
                        if (cashSplitItemsArr != null && cashSplitItemsArr.size() > 0) {
                            for (Object cashSplitItem : cashSplitItemsArr) {
                                if (cashSplitItem != null) {
                                    JSONObject cashSplitItemObj = JSON.parseObject(cashSplitItem.toString());
                                    if (cashSplitItemObj.get("type") != null && "1".equals(cashSplitItemObj.get("type").toString())) {
                                        if (cashSplitItemObj.get("customerId") != null) {
                                            unionbarleyCustomerId = cashSplitItemObj.get("customerId").toString();
                                        }
                                    } else if (cashSplitItemObj.get("type") != null && "3".equals(cashSplitItemObj.get("type").toString())) {
                                        if (cashSplitItemObj.get("customerId") != null) {
                                            linkerCustomerId = cashSplitItemObj.get("customerId").toString();
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }

        Map<String, String> resMap = new HashMap<>();
        resMap.put("linkerTake", linkerTake);
        resMap.put("unionbarleyTake", unionbarleyTake);
        resMap.put("balanceCustomerId", balanceCustomerId);
        resMap.put("linkerCustomerId", linkerCustomerId);
        resMap.put("unionbarleyCustomerId", unionbarleyCustomerId);
        return resMap;
    }


    /**
     * 获取超时订单
     */
    public List<Map> getOvertimeList() {
        return refundDao.getOvertimeList();
    }


    /**
     * 超时自动操作
     *
     * @param: protectCode 维权编号
     * @param: refundStatus 退款状态   0未申请退款1申请退款 2等待发货 3等待收货 4拒绝收货 5同意退款 6退款成功 7退款失败
     * @param: recId 订单商品表id
     * @param: refundType 售后类型：0仅退款1退款并退货
     * @Return: void
     * @Author: ch
     * @Date: 2020/02/12 14:48
     * @Version: 1.11.10
     **/
    public void updateStatusOvertime(Map<String, Object> params) {
        if (params.get("refundStatus") != null) {
            Integer refundStatus = Integer.valueOf(params.get("refundStatus").toString());
            Integer refundType = Integer.valueOf(params.get("refundType").toString());
            String consultStatus = "";
            String consultContent = "";
            if (refundStatus == 1) {
                if (refundType == 0) {
                    refundStatus = 5;
                } else if (refundType == 1) {
                    refundStatus = 2;
                }
            } else if (refundStatus == 3) {
                refundStatus = 5;
            } else if (refundStatus == 2 || refundStatus == 4 || refundStatus == 7) {
                refundStatus = 0;
            }
            params.put("refundStatus", refundStatus);
            refundDao.updaterefundStatus(params);
            RefundParamPo rePo = refundDao.getRefundParamPo(params);
            if (refundStatus == 2) {
                //等待发货(同意退款退货)
                LOGGER.info("等待发货(规定时间内未操作，系统自动同意退款给买家,等待买家退货)");
                consultStatus = "规定时间内未操作，系统自动同意退款给买家,等待买家退货";
                consultContent = "退货地址：" + rePo.getReturnAddress() + "，" + rePo.getReturnPeople() + "，" + rePo.getReturnPhone();
            } else if (refundStatus == 5) {
                //同意退款
                LOGGER.info("规定时间内未操作，系统自动同意退款");
                consultStatus = "规定时间内未操作，系统自动同意退款给买家，本次维权结束";
                consultContent = "退款金额：¥" + rePo.getRefundAmount();
                try {
                    refundToUser(rePo);
                } catch (Exception e) {
                    LOGGER.info("退款异常！", e);
                }
            } else if (refundStatus == 0) {
                //撤销退款
                LOGGER.info("规定时间内未操作，系统自动撤销退款，退款关闭。");
                consultStatus = "规定时间内未操作，系统自动撤销退款，退款关闭。";
                //结算中心账单修改
                protectRecordService.revokeAction(rePo.getOrderSn(), rePo.getOrgId(), rePo.getRecId(), refundStatus);
            }
            params.put("consultStatus", consultStatus);
            params.put("consultContent", consultContent);
            addConsultOvertime(params);
        }
    }

    public void addConsultOvertime(Map<String, Object> params) {
        //发起方系统
        params.put("consultObj", 0);
        if (!StringUtils.isEmpty(params.get("consultImages"))) {
            String consultImages = JSONArray.toJSONString(params.get("consultImages"));
            params.put("consultImages", consultImages);
        }
        refundDao.addConsult(params);
    }

    /**
     * 查看微信退款状态参数
     */
    public List<Map<String, String>> refundQueryList() {
        return refundDao.refundQueryList();
    }
}
